package test.yzx.pproject;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;

public class SimpleRippleView extends FrameLayout{
    public SimpleRippleView(Context context) {
        super(context);
        setWillNotDraw(false);
    }

    public SimpleRippleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setWillNotDraw(false);
    }

    public SimpleRippleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setWillNotDraw(false);
    }


    private int currentRadius;
    private boolean inAnim = false;
    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    {
        paint.setStyle(Paint.Style.FILL);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int width = getWidth();
        int height = getHeight();
        int maxRadius = Math.max(width, height)/2;

        canvas.translate(width/2, height/2);
        int a = 255 - (int)((float)currentRadius/(float)maxRadius*255f);
        paint.setColor(Color.argb(a, 0, 0, 0));
        canvas.drawCircle(0, 0, currentRadius, paint);
    }

    public void startRipple(final int duration){
        if(inAnim) return ;
        post(new Runnable() {
            public void run() {
                inAnim = true;
                currentRadius = 0;
                ValueAnimator anim = ValueAnimator.ofInt(0, Math.max(getHeight()/2, getWidth()/2)).setDuration(duration);
                anim.setInterpolator(new DecelerateInterpolator(1.5f));
                anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    public void onAnimationUpdate(ValueAnimator animation) {
                       int now = (int) animation.getAnimatedValue();
                        currentRadius = now;
                        invalidate();
                    }
                });
                anim.addListener(new Animator.AnimatorListener() {
                    public void onAnimationStart(Animator animation) {
                    }
                    public void onAnimationEnd(Animator animation) {
                        inAnim = false;
                    }
                    public void onAnimationCancel(Animator animation) {
                        inAnim = false;
                    }
                    public void onAnimationRepeat(Animator animation) {
                    }
                });
                anim.start();
            }
        });
    }

}
